//
//  LWOAuthVC.swift
//  Swift_Weibo_HLW
//
//  Created by huanglinwang on 16/9/20.
//  Copyright © 2016年 Linwang. All rights reserved.
//

import UIKit
import SVProgressHUD

let WeiboAppKey = "3653435585"
let WeiboRedirect_Uri = "http://www.baidu.com"
let WeiboAppSecret = "eaddeb3c115be728841d882c22ec155c"
class LWOAuthVC: UIViewController {

    private lazy var webView: UIWebView = UIWebView()
    
    // MARK: -  重写loadView
    override func loadView() {
        
        view = webView
        //处理webView没加载出来时候的底部黑边问题
        webView.isOpaque = false
//        设置代理
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        requestLogin()
        
        setUINav()
    }
    
    
    
    private func requestLogin(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
     
        print(urlString)
        
        let url = URL(string: urlString)
        
        
        
        let urlRequest = URLRequest(url: url!)
        
        
        webView.loadRequest(urlRequest)
        
    }
    
    
    
    func setUINav() {
        
        navigationItem.title = "微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancleAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }
    
    @objc private func cancleAction() {
        
//        print("取消")
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
        
    }
    
    @objc private func autoFill() {
        
//        print("自动填充")
        
        
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '15235159830';document.getElementById('passwd').value = '061621'")
    }
}
//扩展实现代理方法
extension LWOAuthVC: UIWebViewDelegate{
    // MARK: - 开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
    //将要加载请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //判断url是否合法
        guard let url = request.url else {
//            print("url为nil")
            return false
        }
        //绝对路径
//        url.absoluteString
        //判断字符串打头
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri)  {
            
            return true
            
        }
        //执行到此表示是我们关心的
        //直接获取code
        //取地址栏中的参数 并且保证前缀是code=
        if let query = url.query ,query.hasPrefix("code="){
            //从这个位置开始截取 到结束
            print(url.absoluteString)
            print(url.query)
            let code = query.substring(from: "code=".endIndex)
            print(code)
            
            LWUserAccountViewModel.sharedUserAccoutnViewModel.requestAccessToken(code: code, callBack: { (isSuccess) in
                if isSuccess{
//                    print("登陆成功")
                    
                    
                    //!!!!要等到dismiss完成以后再发送切换根视图控制器的操作
                    
                    self.dismiss(animated: false, completion: { 

                        // 进入欢迎页面  使用通知
                        NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotification), object: self)
                        
                    })
                    
                }
            })
        }else{
            
            //不授权就dismiss
            self.dismiss(animated: false, completion: { 
                SVProgressHUD.dismiss()
            })
        }
        

        
        return true
    }
}





